package nsn.message.aggregator.wizzards;

import java.util.HashMap;
import java.util.Map;


import nsn.message.aggregator.model.ISourceType;

import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

/**
 * 
 * 
 * @author Lukasz Nowak
 * @since 10-03-2011
 * 
 */
public final class NewSourcePage extends WizardPage {
	private Text[] texts;
	private Composite container;
	private Composite _parent;

	private ISourceType _sourceType;

	/**
	 * 
	 */
	public NewSourcePage() {
		super("New Source", "New Source", null);
	}

	/**
	 * 
	 * 
	 * @param sourceType
	 */
	public NewSourcePage(final ISourceType sourceType) {
		this();
		_sourceType = sourceType;
	}

	/**
	 * 
	 * 
	 * @param sourceType
	 */
	public void setSourceType(final ISourceType sourceType) {
		_sourceType = sourceType;

	}

	@Override
	public void createControl(Composite parent) {
		_parent = parent;

		initLayout();

		// Required to avoid an error in the system
		setControl(container);
		setPageComplete(false);

	}

	/**
	 * 
	 *
	 */
	public void initLayout() {

		if (container != null && !container.isDisposed()) {
			container.dispose();
		}

		container = new Composite(_parent, SWT.NULL);
		final GridLayout layout = new GridLayout();
		container.setLayout(layout);
		layout.numColumns = 2;

		if (_sourceType == null) {
			return;
		}

		final GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		texts = new Text[_sourceType.parameters().length];
		for (int i = 0; i < texts.length; i++) {
			final int y = i;
			Label label = new Label(container, SWT.NULL);
			label.setText(_sourceType.parameters()[i]);

			texts[i] = new Text(container, SWT.BORDER | SWT.SINGLE);
			texts[i].setText("");
			texts[i].setLayoutData(gd);
			texts[i].addModifyListener(new ModifyListener() {

				@Override
				public void modifyText(ModifyEvent e) {
					if (!texts[y].getText().isEmpty()) {
						setPageComplete(true);
					}

				}
			});

		}
		container.getShell().layout(true, true);
		setControl(container);
	}

	/**
	 * 
	 * 
	 * @return Map<String, String>
	 */
	protected Map<String, String> getValues() {
		final Map<String, String> values = new HashMap<String, String>();
		for (int i = 0; i < texts.length; i++) {
			values.put(_sourceType.parameters()[i], texts[i].getText());
		}
		return values;

	}
}